<template>
  <div class="container">
    <el-card style="height: 80px">
      <div class="top">
        <!-- //上面的表单 -->
        <el-form>
          <el-form-item label="用户名：">
            <el-input
              style="width: 200px"
              placeholder="请你输入搜索用户名"
              v-model="keyword"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="button">
          <el-button type="primary" @click="search" :disabled="keyword ? false : true">
            搜索
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </div>
      </div>
    </el-card>
    <!-- 表格 -->
    <el-card style="margin: 10px 0">
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button type="primary" @click="removeUserList" :disabled="userList.length ? false : true">
        批量删除
      </el-button>
      <el-table :data="formData" border style="margin: 10px 0" @selection-change="selectchange">
        <el-table-column type="selection" />
        <el-table-column align="center" type="index" label="#" />
        <el-table-column prop="id" label="用户id" />
        <el-table-column prop="username" label="用户姓名" />
        <el-table-column prop="nickName" label="用户名称" />
        <el-table-column prop="roleName" label="用户角色" />
        <el-table-column prop="gmtCreate" label="创建时间" />
        <el-table-column prop="gmtModified" label="更新时间" />
        <el-table-column label="操作" width="300px">
          <template #default="{ row }">
            <el-button type="primary" @click="setRole(row)">分配角色</el-button>
            <el-button type="primary" @click="editUser(row)">编辑</el-button>
            <el-popconfirm
              :title="`你确定要删除${row.username}么`"
              width="260px"
              @confirm="removeUser(row.id)"
            >
              <template #reference>
                <el-button type="primary">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- //分页器 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="getHasUser"
        @size-change="sizeChange"
      />
    </el-card>
  </div>
  <!-- 点击添加按钮弹出的抽屉 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ userParams.id ? '修改用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="forms">
        <el-form-item label="用户姓名" prop="username">
          <el-input placeholder="请输入用户姓名" v-model="userParams.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input placeholder="请输入用户昵称" v-model="userParams.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input placeholder="请输入用户密码" v-model="userParams.password"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <!-- @click="confirmClick" -->
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 分配角色抽屉 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
      <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role" :value="role">
          {{ role.roleName }}
        </el-checkbox>
      </el-checkbox-group>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
//引入api
import {
  reqUserinfo,
  reqAddUserOrUpdataUser,
  reqRemoveUser,
  reqRemoveList,
  reqAllRole,
} from '@/api/acl/user'
import type { UserResponseData, User, RoleResponseData, AllRole } from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
//获取setting
import useLayOutSettingStore from '@/stores/modules/setting'
//默认第几页
const currentPage = ref<number>(1)
//每页显示条数
const pageSize = ref<number>(10)
//数据总数
const total = ref<number>()
//表单数据
const formData = ref<any>()
//控制添加功能的抽屉是否显示
const drawer = ref<boolean>(false)
//新增或者修改收集数据
const userParams = reactive<User>({
  id: 0,
  username: '',
  password: '',
  nickName: '',
  gmtCreate: '',
})
//获取setting仓库
const setStores = useLayOutSettingStore()
const forms = ref()
//批量删除的id
const userList = ref<User[]>([])
//关键字
const keyword = ref<string>('')
//分配抽屉的显示和隐藏
const drawer1 = ref(false)
//控制多选框是否权限，true是全选，false是不全选
const checkAll = ref(false)
//设置不确定样式
const isIndeterminate = ref(true)
const userRole = ref<AllRole>([])
//所有角色
const allRole = ref<AllRole>([])
//获取已有的用户信息
const getHasUser = async (page = 1) => {
  currentPage.value = page
  const result: UserResponseData = await reqUserinfo(
    currentPage.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 20000) {
    total.value = result.data.total
    formData.value = result.data.items
  }
}
onMounted(() => {
  getHasUser()
})
//每页展示调试变化
const sizeChange = () => {
  getHasUser()
}
//点击添加用户按钮触发的事件
const addUser = () => {
  drawer.value = true
  //清空数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    password: '',
    nickName: '',
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    forms.value.clearValidate('username')
    forms.value.clearValidate('nickName')
    forms.value.clearValidate('password')
  })
}
//点击取消按钮
const cancelClick = () => {
  drawer.value = false
}
const editUser = (row: any) => {
  Object.assign(userParams, row)
  drawer.value = true
  nextTick(() => {
    forms.value.clearValidate()
  })
}
//保存按钮的回调
const save = async () => {
  await forms.value.validate()
  const result: any = await reqAddUserOrUpdataUser(userParams)
  if (result.code == 20000) {
    //关闭抽屉
    drawer.value = false
    //提示消息
    ElMessage({
      type: 'success',
      message: userParams.id ? '修改成功' : '添加成功',
    })
    // getHasUser(userParams.id?currentPage.value:1)
    window.location.reload()
  } else {
    drawer.value = false
    //提示消息
    ElMessage({
      type: 'error',
      message: userParams.id ? '修改失败' : '添加失败',
    })
  }
}
const validatorUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名至少5位'))
  }
}
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('密码至少6位'))
  }
}
const validatorNickName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('昵称至少5位'))
  }
}
//校验规则
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
  nickName: [{ required: true, trigger: 'blur', validator: validatorNickName }],
}
//删除一个用户
const removeUser = async (usreid: string) => {
  const result = await reqRemoveUser(usreid)
  if (result.code == 20000) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(formData.value.length > 1 ? currentPage.value : currentPage.value - 1)
  } else {
    ElMessage({
      type: 'success',
      message: '删除失败',
    })
  }
}
//table复选框被构选会触发的事件
const selectchange = (value: any) => {
  userList.value = value
}
//点击批量删除触发的事件
const removeUserList = async () => {
  //准备好用户id数组
  const idList = userList.value.map((item: any) => {
    return item.id
  })
  const result: any = await reqRemoveList(idList)
  if (result.code == 20000) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(formData.value.length > 1 ? currentPage.value : currentPage.value - 1)
  } else {
    ElMessage({
      type: 'success',
      message: '删除失败',
    })
  }
}
//搜索
const search = () => {
  getHasUser()
  keyword.value = ''
}
//重置
const reset = () => {
  setStores.refsh = !setStores.refsh
}
//分配角色
const setRole = async (row: User) => {
  // drawer1.value=true
  Object.assign(userParams, row)
  const result: RoleResponseData = await reqAllRole(row.id as number)
  if (result.code == 20000) {
    allRole.value = result.data.allRolesList
    userRole.value = result.data.assignRoles
    drawer1.value = true
  }
}
//全选按钮触发
const handleCheckAllChange = (val: any) => {
  userRole.value = val ? allRole : []
  isIndeterminate.value = false
}
//
const handleCheckedCitiesChange = (value: string[]) => {
  const roleCount = value.length
  checkAll.value = roleCount == allRole.value.length
  isIndeterminate.value = roleCount > 0 && roleCount < allRole.value.length
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  /* background: pink; */
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
